<?php
/*
 * @Description: file content
 * @FilePath: \auxface_api\app\certificate\controller\admin\v1\file\Type.php
 */

declare(strict_types=1);

namespace app\certificate\controller\admin\v1\file;

use think\facade\Db;
use think\Request;

class Type
{
    /**
     * @Description: 
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data  = $request->data;
        $limit =  $data['limit'];
        $page =  $data['page'];

        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', 0]
        ];

        if (!empty($data['name'])) array_push($where, ['name', 'like', $data['name'] . "%"]);

        $list = DB::table('certificate_fileType')
            ->where($where)
            ->field(['name', 'remark', 'inDate', 'uuid', 'isSecond','subtitle'])
            ->order('id desc')
            ->page((int)$page, (int)$limit)
            ->select()
            ->toArray();
        foreach ($list as &$item) {
            $item['hasFiles'] = DB::table('certificate_fileTypeLink')->where('fileTypeUuid', $item['uuid'])->find() ? 1 : 0;
        }
        

        $count = DB::table('certificate_fileType')
            ->where($where)
            ->count();

        $data = compact('list', 'count');

        return result(SUCCESS, $data);
    }
    /**
     * @Description: 
     * @param {Request} $request
     */
    public function create(Request $request)
    {
        $data = $request->data;
        if($data['isSecond']  == 1 && empty($data['content'])) result(FAIL, '', '具体内容不能为空');
        $insert =  [
            'uuid' => createUuid(),
            'projectCode' => $request->prjCode,
            'corpCode' => $request->corpCode,
            'name' => $data['name'],
            'remark' => $data['remark'] ?? '',
            'isSecond' => $data['isSecond'],
            'content' => json_encode($data['content'] ?? [], JSON_UNESCAPED_UNICODE),
            'subtitle' => $data['subtitle'] ?? '',
        ];
        DB::table('certificate_fileType')->insert($insert);

        return result(SUCCESS, ['uuid' => $insert['uuid'], 'inDate' => date('Y-m-d H:i:s')], '添加成功!');
    }

    /**
     * @Description: 修改
     */
    public function update(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];

        $cehck = DB::table('certificate_fileType')->where([
            ['uuid', '<>', $uuid],
            ['name', '=', $data['name']],
            ['isDelete', '=', 0],
        ])->value('id');
        if ($cehck) return result(FAIL, '', '名称已存在,无法修改!');
        if($data['isSecond']  == 1 && empty($data['content'])) result(FAIL, '', '具体内容不能为空');
        $updateData = [
            'name' => $data['name'],
            'remark' => $data['remark'] ?? '',
            'isSecond' => $data['isSecond'],
            'content' => json_encode($data['content'] ?? [], JSON_UNESCAPED_UNICODE),
            'subtitle' => $data['subtitle'] ?? '',
        ];
        DB::table('certificate_fileType')->where('uuid', $uuid)->update($updateData);
        return result(SUCCESS, '', '更改成功');
    }

    public function destroy(Request $request)
    {
        $data = $request->data;
        DB::table('certificate_fileType')->where('uuid', $data['uuid'])->update(['isDelete' => 1]);

        //删除类型关联的附件类型
        $machineRiskTypeList = DB::table('certificate_machineRiskType')->where('fileTypeUuids', 'like', '%' . $data['uuid'] . '%')->select()->toArray();
        foreach ($machineRiskTypeList as $item) {
            $fileTypeUuids = json_decode($item['fileTypeUuids'], true) ?: [];
            $fileTypeUuids = array_diff($fileTypeUuids, [$data['uuid']]) ?: [];
            DB::table('certificate_machineRiskType')->where('uuid', $item['uuid'])->update(['fileTypeUuids' => json_encode($fileTypeUuids, JSON_UNESCAPED_UNICODE)]);
        }
        return result(SUCCESS, '', '删除成功');
    }

    /**
     * @Description: 获取数据
     * @param {Request} $request
     */
    public function getDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];

        $data = DB::table('certificate_fileType')->where('uuid', $uuid)->field(['inDate', 'corpCode', 'name', 'remark', 'uuid', 'isSecond', 'content','subtitle'])->find();
        $data['content'] = json_decode($data['content'], true);
        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 获取附件数据
     * @param {Request} $request
     */
    public function getFileList(Request $request)
    {
        $data = $request->data;

        $list = DB::table('certificate_file')->alias('ft')
            ->where('isDelete', 0)
            ->field(['name', 'uuid'])
            ->select()->toArray();
        $checked = DB::table('certificate_fileTypeLink')
            ->alias('l')
            ->join('certificate_file f', 'f.uuid = l.fileUuid')
            ->where('l.fileTypeUuid', $data['uuid'])
            ->where('f.isDelete', 0)
            ->column('l.fileUuid');
        $data = compact('list', 'checked');
        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 修改附件数据
     * @param {Request} $request
     */
    public function changeFile(Request $request)
    {
        $data = $request->data;
        $values = $data['value'];
        DB::startTrans();
        try {
            DB::table('certificate_fileTypeLink')->where('fileTypeUuid', $data['uuid'])->delete();
            foreach ($values as $key => $value) {
                $insertData[] = ['fileTypeUuid' => $data['uuid'], 'uuid' => createUuid(), 'fileUuid' => $value];
            }
            DB::table('certificate_fileTypeLink')->insertAll($insertData);
            DB::commit();
            return result(SUCCESS, '', '更新成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return result(FAIL, '', '更新失败');
        }
    }

    /**
     * @Description: 获取字典
     * @param {Request} $request
     */
    public function getOptions(Request $request)
    {
        $where = [
            ['projectCode', '=', $request->authWhere['projectCode']],
            ['isDelete', '=', '0'],
        ];
        $data['fileList'] = DB::table('certificate_file')
            ->where($where)
            ->field(['name', 'remark', 'uuid'])
            ->order('id desc')
            ->select();

        return result(SUCCESS, $data, '');
    }
}
